package com.gxuwz.endrskyweather.viewmodel;

import android.app.Application;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.gxuwz.endrskyweather.model.City;
import com.gxuwz.endrskyweather.repository.FavoriteRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class CityManagerViewModel extends AndroidViewModel {
    private FavoriteRepository repository;
    private MutableLiveData<List<City>> nonDefaultCities;
    private MutableLiveData<City> defaultCity;
    private MutableLiveData<Boolean> deleteFlag;

    public CityManagerViewModel(Application application) {
        super(application);
        repository = new FavoriteRepository(application);
        nonDefaultCities = new MutableLiveData<>();
        defaultCity = new MutableLiveData<>();
        deleteFlag = new MutableLiveData<>();
    }

    // 设置默认城市
    public void setDefaultCity(City city) {
        try {
            boolean result = repository.setDefaultCity(city.getAreaCode());
            if (result) {
                loadDefaultCity();
                loadNonDefaultCities();
                Log.d("CityManagerViewModel", "loadDefaultCity: " + Objects.requireNonNull(getDefaultCity().getValue()).getAreaCn());
                Log.d("CityManagerViewModel", "Default city set to: " + city.getAreaCn());
            }
        } catch (Exception ex) {
            Log.e("CityManagerViewModel", "Error setting default city: " + ex.getMessage());
        }
    }

    // 获取非默认城市列表LiveData
    public LiveData<List<City>> getNonDefaultCities() {
        return nonDefaultCities;
    }


    // 获取删除结果反馈
    public LiveData<Boolean> getDeleteFlag() {
        return deleteFlag;
    }

    // 获取默认城市LiveData
    public LiveData<City> getDefaultCity() {
        return defaultCity;
    }

    // 获取合并后的城市列表
    public LiveData<List<City>> getCombinedCities() {
        MutableLiveData<List<City>> combinedCities = new MutableLiveData<>();
        
        // 合并默认城市和非默认城市
        getDefaultCity().observeForever(defaultCity -> {
            getNonDefaultCities().observeForever(nonDefaultCities -> {
                List<City> cities = new ArrayList<>();
                if (defaultCity != null) {
                    cities.add(defaultCity);
                }
                if (nonDefaultCities != null) {
                    cities.addAll(nonDefaultCities);
                }
                combinedCities.setValue(cities);
            });
        });
        
        return combinedCities;
    }

    // 加载默认城市数据
    public void loadDefaultCity() {
        new Thread(() -> {
            try {
                String[] defaultCityInfo = repository.getDefaultCity();
                if (defaultCityInfo != null) {
                    defaultCity.postValue(new City(defaultCityInfo[0], defaultCityInfo[1]));
                } else {
                    defaultCity.postValue(null);
                }
            } catch (Exception ex) {
                Log.e("CityManagerViewModel", "Error fetching default city: " + ex.getMessage());
            }
        }).start();
    }

    // 加载非默认城市数据
    public void loadNonDefaultCities() {
        new Thread(() -> {
            try {
                List<City> cities = new ArrayList<>();
                Cursor cursor = repository.getAllFavorites();
                while (cursor.moveToNext()) {
                    String areaCode = cursor.getString(cursor.getColumnIndex("favorite_area_code"));
                    String areaName = cursor.getString(cursor.getColumnIndex("favorite_area_cn"));
                    Integer defaultFlag = cursor.getInt(cursor.getColumnIndex("favorite_default_flag"));
                    if (defaultFlag == 0) {
                        cities.add(new City(areaCode, areaName));
                    }
                }
                cursor.close();
                Log.d("CityManagerViewModel", "Loaded " + cities.size() + " non-default cities");
                nonDefaultCities.postValue(cities);
            } catch (Exception e) {
                Log.e("CityManagerViewModel", "Error loading non-default cities: " + e.getMessage());
            }
        }).start();
    }

    // 删除收藏的城市
    public void deleteCity(City city) {
        new Thread(() -> {
            try {
                boolean result = repository.deleteFavoriteCity(city.getAreaCode());
                deleteFlag.postValue(result);
                if (result) {
                    loadNonDefaultCities();
                }
            } catch (Exception e) {
                Log.e("CityManagerViewModel", "Error deleting city: " + e.getMessage());
            }
        }).start();
    }

}

